package com.xwb.laboratory.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(8080);
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			try {
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}));
		System.out.println("tomcat 服务器启动成功");
		while(!server.isClosed()) {
			Socket request = server.accept();
			System.out.println("收到请求：" + request.toString());
			InputStream inputStream = request.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
			String msg = null;
			String responseMsg = "";
			while((msg = reader.readLine()) != null) {
				if(msg.length() == 0 || "end".equals(msg)) {
					break;
				}
				System.out.println(msg);
				responseMsg += msg;
			}
			System.out.println("--------------------end");
			//OutputStream outputStream = request.getOutputStream();
			//BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
			//writer.write("响应信息：" + responseMsg);
			request.getOutputStream().write(("响应信息：" + responseMsg + "\r\n").getBytes("utf-8"));
			request.getOutputStream().flush();
			System.out.println("响应成功!");
		}
		server.close();
	}
}
